// 保留正确的导入语句
import { defineAsyncComponent, h, ref } from 'vue';
import { SortAscendingOutlined, SortDescendingOutlined } from '@ant-design/icons-vue';

import { requestClient } from '#/api/request';

// 异步导入 Ant Design Vue 组件
const AutoComplete = defineAsyncComponent(
  () => import('ant-design-vue/es/auto-complete'),
);
const Dropdown = defineAsyncComponent(
  () => import('ant-design-vue/es/dropdown'),
);
const Input = defineAsyncComponent(() => import('ant-design-vue/es/input'));

interface RenderOptions {
  filterData: Record<string, any>;
  sortData: Record<string, any>;
  url?: string;
  pickerDate?: [Date, Date];
  formData?: Record<string, any>;
  checkedGridClassIds?: any[];
  onFilterChange?: () => void;
  onSorterChange?: () => void;
  isSort?: boolean;
}

export function renderFilterHeader(params: any, options: RenderOptions) {
  const {
    filterData,
    sortData,
    url,
    pickerDate,
    formData,
    checkedGridClassIds,
    onFilterChange,
    onSorterChange,
    isSort = true,
  } = options;

  const suggestions = ref<any[]>([]);
  const noData = ref(false);
  const showDropdown = ref(false);
  const searching = ref(false);

  const fetchSuggestions = async (queryStr: string) => {
    suggestions.value = [];
    noData.value = false;
    searching.value = true;

    if (!url) {
      searching.value = false;
      return;
    }

    try {
      const { data } = await requestClient.post(url, {
        heardAutoCompleteName: params.column.property,
        keyword: queryStr,
        pickerDate,
        filterData,
        formData,
        checkedGridClassIds,
      });

      const results = 
        data.list?.map((item: any) => ({
          value: `${item.value}`,
          label: item.label || `${item.value}`,
        })) || [];

      if (results.length === 0) {
        noData.value = true;
        suggestions.value = [
          {
            value: '',
            label: '无匹配数据',
            isNoDataItem: true,
          },
        ];
      } else {
        suggestions.value = results;
      }
    } catch (error) {
      console.error('获取搜索建议失败:', error);
      suggestions.value = [];
      noData.value = true;
    } finally {
      searching.value = false;
    }
  };

  const handleSort = (order: string) => {
    sortData[params.column.property] = order;
    if (onSorterChange) {
      onSorterChange();
    }
  };

  const renderSorter = () => {
    const currentSort = sortData[params.column.property];

    return h(
      Dropdown,
      {
        trigger: ['click'],
        placement: 'bottomRight',
      },
      {
        default: () => h(
          'div',
          {
            className: 'sorter-icon',
            onClick: (e: Event) => e.preventDefault(),
          },
          h(SortAscendingOutlined, { style: { fontSize: '16px' } }),
        ),
        menu: () => h(
          'ul',
          {
            className: 'ant-dropdown-menu',
            style: { width: '80px' },
          },
          [
            h(
              'li',
              {
                className: 'ant-dropdown-menu-item',
                onClick: () => handleSort('asc'),
              },
              '升序',
            ),
            h(
              'li',
              {
                className: 'ant-dropdown-menu-item',
                onClick: () => handleSort('desc'),
              },
              '降序',
            ),
            h(
              'li',
              {
                className: 'ant-dropdown-menu-item',
                onClick: () => handleSort(''),
              },
              '重置',
            ),
          ],
        ),
      },
    );
  };

  const renderAutocomplete = () => {
    // 修复combobox模式不支持optionLabelProp的问题
    // 1. 移除optionLabelProp属性
    // 2. 确保数据结构正确
    return h(
      AutoComplete,
      {
        value: filterData[params.column.property] || '',
        onChange: (value: string) => {
          filterData[params.column.property] = value;
          fetchSuggestions(value);
        },
        allowClear: true,
        placeholder: '输入关键字搜索',
        options: suggestions.value,
        // 正确设置open属性
        open: showDropdown.value,
        onOpenChange: (open: boolean) => {
          showDropdown.value = open;
        },
        onFocus: () => {
          if (filterData[params.column.property]) {
            fetchSuggestions(filterData[params.column.property]);
          }
        },
        onBlur: () => {
          setTimeout(() => {
            showDropdown.value = false;
          }, 200);
        },
        // 选项选择处理函数 - 调整参数以适应combobox模式
        onSelect: (value: string) => {
          filterData[params.column.property] = value;
          showDropdown.value = false;
          if (onFilterChange) {
            onFilterChange();
          }
        },
        // 可以显式设置mode为非combobox模式（如果不需要combobox功能）
        // mode: 'default',
      },
      // 添加默认插槽以正确渲染输入框
      {
        default: () => h(Input)
      }
    );
  };

  return h('div', { className: 'filter-header' }, [
    h('div', { className: 'header-title' }, [
      h('span', { className: 'title-text' }, params.column.title),
      isSort && renderSorter(),
    ]),
    h(
      'div',
      {
        className: 'header-filter',
      },
      renderAutocomplete(),
    ),
  ]);
}
